package com.training.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.training.client.TestFeignClient;
import com.training.entity.RoleUser;
import com.training.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@Tag(name = "管理员登录控制器")
public class LoginController {

    private final TestFeignClient testFeignClient;

    @Autowired
    public LoginController(TestFeignClient testFeignClient) {
        this.testFeignClient = testFeignClient;
    }

    @Operation(summary = "管理员登录")
    @PostMapping("/login")
    public SaResult login(@RequestBody User user) {
        //查询user表和user_role表，找到code为user.getCode()的用户
        User userOne = Db.lambdaQuery(User.class).eq(User::getCode, user.getCode()).oneOpt()
                .orElseThrow(() -> new RuntimeException("账号不存在"));
        Db.lambdaQuery(RoleUser.class).eq(RoleUser::getUserId, userOne.getId()).eq(RoleUser::getRoleId, 1).oneOpt()
                .orElseThrow(() -> new RuntimeException("非管理员账号"));
        if(!userOne.getPassword().equals(user.getPassword())){
            throw new RuntimeException("密码错误");
        }
        //登录
        StpUtil.login(userOne.getId());
        log.warn("登录成功");
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        return SaResult.ok("登录成功").setData(tokenInfo);
    }

    @Operation(summary = "管理员注销")
    @PostMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("注销成功");
    }

    @GetMapping("/test")
    public String test() {
        return testFeignClient.test();
    }
}
